package hapi.util;

class LazyLoader<T> implements Dynamic {
	
	var __inst:T;
	var __loader:Void->T;
	var __loaded:Bool;
	
	public function new(loader:Void->T, interfaceToIntercep:Dynamic ) {
		this.__loaded = false;
		for(fname in Type.getInstanceFields(interfaceToIntercep)){
			Reflect.setField(this, fname, __methodInterceptor(fname));
		}
	}
	
	function __methodInterceptor(methodName:String) {
		var self = this;
		var method = Reflect.field(self.__inst, methodName);
		var f = function(args:Array<Dynamic>) {
			if (!self.__loaded) { 
				self.__inst = self.__loader();
				self.__loaded = true;
				method = Reflect.field(self.__inst, methodName);
			}
			trace("call " + args);
			var r = Reflect.callMethod(self.__inst, method, args);
			return r;
		}
		return Reflect.makeVarArgs(f);
	}
}